package com.database.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.database.common.Service;
import com.database.db.ConnectionFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-02-28.
 *
 * @author zhoufy
 */
@Service
public class ConnectionUtils {



    /**
     * 储存当前线程连接
     */
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();


    /**
     * 从当前线程获取连接
     *
     * @return
     * @throws Exception
     */
    public Connection getCurrentThreadConn() throws SQLException {
        /**
         * 判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
         */
        Connection connection = threadLocal.get();
        if (connection == null) {
            // 从连接池拿连接并绑定到线程
            connection = ConnectionFactory.getInstance().getConnection();
            // 绑定到当前线程
            threadLocal.set(connection);
        }
        return connection;

    }


}
